home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: news.uunet.ca!wildcan!sq!news
- From: willer@carolian.com (Steve Willer)
- Subject: Re: auto_ptr capability question
- Message-ID: <3160321d.335010145@sqarc.sq.com>
- Sender: news@sq.com (News Administrator)
- Organization: Carolian Systems, Toronto ON
- X-Newsreader: Forte Agent .99d/32.182
- References: <31600aa3.1288774@news.xmission.com>
- Date: Mon, 1 Apr 1996 19:55:40 GMT
-
- macron@xmission.com (Joe Schlimgen) wrote:
-
- >Can anyone provide a reason why the designers of the STL (who, I would
- >think, are much more knowledgeable about C++ and OOP than I) would
- >choose to provide an explicit rather than an implicit function? I see no
- >potential problems with an implicit conversion (but I could very well be
- >wrong).
-
- First of all, auto_ptr is not part of the STL. It's part of the
- standard C++ library. The "STL" encompasses the containers like list
- and vector, iterators, and algorithms such as sort() and transform().
-
- Now, as for explicit versus implicit...it's for the same reason that
- std::string doesn't have an implicit conversion to "const char *":
- It's dangerous, and bugs can creep in undetected. I'm perfectly happy
- having to type a few more characters in order to avoid subtle bugs in
- my code. For a detailed explanation, check Meyers's "More Effective
- C++" book, item #5.
-
- >Also, I've noticed that the assignment from another auto_ptr function
- >(also shown below) causes the auto_ptr being assign *from* to release
- >ownership (as it should) but does *not* delete the (possible) pointer
- >that is being assigned *to*, thus possibly causing a memory leak.
-
- Ownership is being _transferred_. Note that if you have something
- like:
-
- auto_ptr<T> a;
- auto_ptr<T> b(new T);
- a = b;
-
- What this means is that at the second line, "b" owns a T, and "a" owns
- nothing. When you say "a=b", "a" now owns the T and "b" owns nothing.
- At the third line, no new T's are created -- the one T that got
- explicitly created is simply passed around.
-
- > X* get () const { return the_p; } // Provided by the STL
- > X* operator X* () const { return the_p; } // Not provided by the STL
-
- You should remove this. Not only is it bad practice, but it's also not
- part of the standard auto_ptr.
-
- > void operator= (auto_ptr<X>& rhs) { reset(rhs.release()); }
- > X* reset (X* p = 0) { X* tmp = the_p; the_p = p; return tmp; }
-
- auto_ptr<T>::reset() deletes the current pointer and sets the current
- pointer to the given pointer.
- auto_ptr<T>::release() sets the current pointer to zero and returns
- the old value. It does _not_ delete the structure.
-
- So, perhaps an English form of this function is "reset my own pointer
- with whatever the other guy released".
-
-